package com.radon.kafka.api;

import com.radon.kafka.conf.Constant;
import com.radon.kafka.conf.KafKaConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 生产者测试
 *
 *生产者在发送消息的时候，使用对应的kafkaTemplate即可，如果是多个，需要注意导入的是对应的kafkaTemplate。
 *
 */
@RestController
@RequestMapping("kafka")
public class TestKafKaProducerController {

    private final Logger logger = LoggerFactory.getLogger(TestKafKaProducerController.class);

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @RequestMapping("send")
    public String send(String msg) {

        ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send(Constant.TEST_KAFKA_TOPIC, msg);

        future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {

            @Override
            public void onSuccess(SendResult<String, String> result) {
                logger.info("生产者-发送消息成功：" + result.toString());
                System.out.println("生产者-发送消息成功：" + result.toString());
            }

            @Override
            public void onFailure(Throwable ex) {
                logger.info("生产者-发送消息失败：" + ex.getMessage());
                System.out.println("生产者-发送消息失败：" + ex.getMessage());
            }
        });


        return "test-ok";
    }
}
